/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.huawei.spare.part.replace.views.prepare.risk;

import com.huawei.spare.part.replace.framework.SmartContentPresenter;
import com.huawei.spare.part.replace.framework.SmartDataBus;
import com.huawei.spare.part.replace.framework.SmartDatabase;
import com.huawei.spare.part.replace.framework.SmartRouter;
import com.huawei.spare.part.replace.models.Project;
import com.huawei.spare.part.replace.models.Solution;
import com.huawei.spare.part.replace.utils.JsonMapper;
import io.reactivex.Observable;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.Label;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.concurrent.Callable;

/**
 * @author Woo
 */
public class RiskPresenter extends SmartContentPresenter {

    private static final Logger log = LoggerFactory.getLogger(RiskPresenter.class);
    final SimpleObjectProperty<Solution> solution = new SimpleObjectProperty();

    @Override
    public void initialize() {
        Platform.runLater(() -> {
            SmartRouter.get().nextStepButton().setDisable(true);
            final Project project = SmartDataBus.get().getProject();

            final boolean sameSoftwareVersion = project.getDefective().getSoftwareVersion()
                                                       .equalsIgnoreCase(project.getSpare().getSoftwareVersion());

            if (sameSoftwareVersion) {
                final String tip = String.format(getString("risk.error.same.version"), project.getDefective().getSoftwareVersion());
                addLabel(tip, "warning");
            } else {
                Observable.defer((Callable<io.reactivex.Observable<Optional<Solution>>>) () -> {
                    final Optional<Solution> solution = SmartDatabase.get().getReplaceSolution(project, false);
                    return Observable.just(solution);
                }).subscribeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).subscribe((solution) -> {
                    container.getChildren().clear();
                    if (!solution.isPresent()) {
                        addLabel("risk.error.could.not.find.solution", "warning");
                    } else {
                        this.solution.set(solution.get());
                        log.info("Find solution: {}", JsonMapper.nonEmptyMapper().toJson(this.solution.get()));
                        addLabel("common.p.title.risk", "h3");
                        this.solution.get().getRisks().stream().forEachOrdered(risk -> {
                            addLabel(risk, "div-16");
                        });

                        addLabel("common.p.title.suggestion", "h3");
                        this.solution.get().getSuggestions().stream().forEachOrdered(suggestion -> {
                            addLabel(suggestion, "div-16");
                        });

                        SmartRouter.get().nextStepButton().setDisable(false);
                    }
                }, (error) -> {
                    addLabel("risk.error.could.not.parse.solution", "warning");
                    log.error("Failed to parse solution database", error);
                });
            }
        });
    }

    private void addLabel(String s, String styleClass) {
        final Label label = new Label(getString(s));
        label.setWrapText(true);
        label.getStyleClass().add(styleClass);
        container.getChildren().add(label);
    }

    @Override
    public Observable<Boolean> onFinish() {
        final Project project = SmartDataBus.get().getProject();
        project.setSolution(solution.get());
        return Observable.just(true);
    }

}
